package com.hontlong.aixue.web;

import java.util.List;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.hontlong.aixue.bean.User;
import com.hontlong.aixue.bean.ZhiShi;
import com.hontlong.aixue.service.UserService;
import com.hontlong.aixue.service.ZhiShiService;

//@RequestMapping @RequestParam @PathVariable @ModelAttributes 
//@SessionAttributes @CookieValue @RequestHeader

@Controller
@RequestMapping("/zhishi")
public class ZhiShiController {
	@Autowired
	private ZhiShiService zhishiService;

	private final Logger logger = org.slf4j.LoggerFactory
			.getLogger(ZhiShiController.class);

	@RequestMapping(value="/add",method=RequestMethod.POST)
	public ModelAndView add(@RequestParam(value = "zhishi", required = true) String zhishi){
		logger.debug("zhishi:{}",zhishi);
		ModelMap model = new ModelMap();
		User user = UserService.getCurrentUser();
		if(user==null || user.getUsername()=="guest"){
			model.put("state", "stop");
			model.put("message", "用户没有登录");
		}else{
			zhishiService.add(user,zhishi);
			model.put("state", "ok");
		}
		ModelAndView mv = new ModelAndView("jsonView", model);
		return mv;		
	}

	public ZhiShiService getZhishiService() {
		return zhishiService;
	}

	@RequestMapping("/list")
	public ModelAndView list(
			@RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
			@RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo
			) {
	    	ModelMap model = new ModelMap();
	    	model.put("state", "ok");
	    	model.put("pageNo", pageNo);
	    	int total=zhishiService.total();
	    	int pageTotal=(total+pageSize-1)/pageSize;	    	
		model.put("pageTotal", pageTotal);
	    	if(pageNo<=pageSize){	    	
        		List<ZhiShi> list= zhishiService.list(pageNo, pageSize);
        		model.put("data", list);		
	    	}
		ModelAndView mv = new ModelAndView("jsonView", model);
		return mv;
	}
	
	@RequestMapping("/{username}/list")
	public ModelAndView list(
			@RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
			@RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
			@PathVariable String username) {
		logger.debug("userName="+username);
		List<ZhiShi> list= zhishiService.list(username, pageNo, pageSize);
		ModelMap model = new ModelMap();
		model.put("data", list);
		ModelAndView mv = new ModelAndView("jsonView", model);
		return mv;
	}
	
	public void setZhishiService(ZhiShiService zhishiService) {
		this.zhishiService = zhishiService;
	}
}
